import React, { useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Mic, Settings, Zap, CheckCircle, AlertCircle } from 'lucide-react'
import { useDeviceStore } from '../stores/deviceStore'
import { useSocketStore } from '../stores/socketStore'
import { toast } from '../components/Toast'

const HomePage: React.FC = () => {
  const { 
    deviceId, 
    deviceName, 
    isRegistered, 
    getPairingStatus,
    syncPairingStatus
  } = useDeviceStore()
  
  const { isConnected, socket } = useSocketStore()

  const pairingStatus = getPairingStatus()

  // 只保留 socket-connected 事件自动注册，防止多次注册
  useEffect(() => {
    const handleSocketConnected = async (event: CustomEvent) => {
      const { socket: connectedSocket } = event.detail
      try {
        const store = useDeviceStore.getState()
        console.log('device store', store)
        if (!store.deviceId) {
          await store.initializeDevice()
        }
        if (!store.isRegistered) {
          await store.registerDevice(connectedSocket)
        }
        
        // 连接成功后同步配对状态
        if (store.deviceId) {
          console.log('🔄 连接成功后同步配对状态...')
          await store.syncPairingStatus(connectedSocket)
        }
      } catch (error) {
        console.error('自动注册设备失败:', error)
      }
    }

    window.addEventListener('socket-connected', handleSocketConnected as unknown as EventListener)
    return () => {
      window.removeEventListener('socket-connected', handleSocketConnected as unknown as EventListener)
    }
  }, [])

  // 当socket连接状态变化时，同步配对状态
  useEffect(() => {
    if (isConnected && socket && deviceId) {
      console.log('🔄 Socket连接状态变化，同步配对状态...')
      syncPairingStatus(socket)
    }
  }, [isConnected, socket, deviceId, syncPairingStatus])

  // 页面加载时强制同步配对状态
  useEffect(() => {
    if (deviceId && syncPairingStatus) {
      syncPairingStatus(socket)
    }
  }, [deviceId, syncPairingStatus, socket])

  const Card = ({ icon, title, description, link, status, cta, disabled = false }: {
    icon: React.ReactNode,
    title: string,
    description: string,
    link?: string,
    status?: React.ReactNode,
    cta: string,
    disabled?: boolean
  }) => (
    <div className={`card ${disabled ? 'opacity-50' : ''}`}>
      <div className="flex items-center space-x-4">
        <div className="flex-shrink-0 w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center">
          {icon}
        </div>
        <div className="flex-1">
          <h3 className="font-semibold text-lg">{title}</h3>
          <p className="text-sm text-gray-600">{description}</p>
        </div>
      </div>
      <div className="mt-4 flex items-center justify-between">
        <div className="text-xs text-gray-500">{status}</div>
        {link ? (
          <Link to={link} className={`btn btn-sm ${disabled ? 'btn-disabled' : 'btn-primary'}`}>
            {cta}
          </Link>
        ) : (
          <button className={`btn btn-sm ${disabled ? 'btn-disabled' : 'btn-primary'}`}>
            {cta}
          </button>
        )}
      </div>
    </div>
  )

  // 移除 renderPairingStatus 相关方法和 Card 配对入口

  return (
    <div className="min-h-screen bg-gray-50 p-4">
      <div className="max-w-md mx-auto space-y-4">
        
        <div className="text-center py-4">
          <h1 className="text-2xl font-bold text-gray-800">智能输入助手</h1>
          <div className="mt-2 space-y-1">
            <p className="text-sm text-gray-600">{deviceName || '移动设备'}</p>
            {deviceId && (
              <div className="flex items-center justify-center space-x-2">
                <span className="text-xs text-gray-500">设备ID:</span>
                <code className="text-xs bg-blue-50 text-blue-700 px-2 py-1 rounded font-mono">
                  {deviceId}
                </code>
                <button 
                  onClick={() => {
                    navigator.clipboard.writeText(deviceId);
                    toast.success('设备ID已复制到剪贴板');
                  }}
                  className="text-xs text-gray-500 hover:text-gray-700"
                  title="复制设备ID"
                >
                  复制
                </button>
              </div>
            )}
          </div>
        </div>

        <Card
          icon={<Mic className="w-6 h-6 text-blue-500" />}
          title="语音输入"
          description="开始语音识别，并将文本发送到电脑。"
          link="/voice"
          status={
            <div className="flex items-center space-x-1">
              <span>已配对</span>
            </div>
          }
          cta="开始输入"
          disabled={pairingStatus !== 'paired'}
        />

        <Card
          icon={<Settings className="w-6 h-6 text-gray-500" />}
          title="应用设置"
          description="调整语音识别和应用参数。"
          link="/settings"
          cta="前往设置"
        />

        {/* 配对状态管理 */}
        {isConnected && deviceId && (
          <div className="card">
            <h4 className="font-semibold mb-2 text-sm">配对状态管理</h4>
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <span>当前状态:</span>
                <span className={`font-medium ${
                  pairingStatus === 'paired' ? 'text-green-600' : 'text-red-600'
                }`}>
                  {pairingStatus === 'paired' ? '已配对' : '未配对'}
                </span>
              </div>
              <div className="flex space-x-2">
                <button 
                  onClick={() => syncPairingStatus(socket)}
                  className="btn btn-sm btn-outline"
                  disabled={!isConnected}
                >
                  刷新状态
                </button>
                {pairingStatus === 'paired' && (
                  <button 
                    onClick={() => {
                      const { disconnectPairing } = useDeviceStore.getState();
                      disconnectPairing();
                    }}
                    className="btn btn-sm btn-outline btn-error"
                  >
                    断开配对
                  </button>
                )}
              </div>
            </div>
          </div>
        )}

        {/* 设备信息 */}
        <div className="card">
          <h4 className="font-semibold mb-3 text-sm">设备信息</h4>
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <span className="text-sm text-gray-600">设备ID:</span>
              <div className="flex items-center space-x-2">
                <code className="text-xs bg-gray-100 px-2 py-1 rounded font-mono text-blue-600">
                  {deviceId || '未生成'}
                </code>
                {deviceId && (
                                  <button 
                  onClick={() => {
                    navigator.clipboard.writeText(deviceId);
                    toast.success('设备ID已复制到剪贴板');
                  }}
                  className="text-xs text-blue-600 hover:text-blue-700"
                  title="复制设备ID"
                >
                  复制
                </button>
                )}
              </div>
            </div>
            <div className="flex justify-between">
              <span className="text-sm text-gray-600">设备名称:</span>
              <span className="text-sm font-medium">{deviceName || '未设置'}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-sm text-gray-600">设备类型:</span>
              <span className="text-sm font-medium">移动设备</span>
            </div>
          </div>
        </div>

        {/* 连接状态 */}
        <div className="card text-xs text-gray-600">
          <h4 className="font-semibold mb-2 text-sm">连接状态</h4>
          <div className="space-y-1">
            <div className="flex justify-between">
              <span>服务器连接:</span>
              <span className={`font-medium ${isConnected ? 'text-green-600' : 'text-red-600'}`}>
                {isConnected ? '已连接' : '未连接'}
              </span>
            </div>
            <div className="flex justify-between">
              <span>设备注册:</span>
              <span className={`font-medium ${isRegistered ? 'text-green-600' : 'text-red-600'}`}>
                {isRegistered ? '已注册' : '未注册'}
              </span>
            </div>
            <div className="flex justify-between">
              <span>配对状态:</span>
              <span className="font-medium">
                {pairingStatus === 'paired' && `已配对`}
                {pairingStatus === 'unpaired' && '未配对'}
                {pairingStatus === 'pairing' && '正在配对...'}
              </span>
            </div>
          </div>
        </div>

        {/* 开发者信息 */}
        <div className="text-center text-xs text-gray-400 pt-4">
          <p>SmartInput v1.0.0</p>
          <p>为高效输入而生</p>
        </div>

      </div>
    </div>
  )
}

export default HomePage 